package ogs.game.core.codec
{
	import com.adobe.serialization.json.JSON;
	
	import flash.utils.ByteArray;
	import flash.utils.Endian;
	
	import ogs.game.core.protocol.GameMsg;
	import ogs.lib.mina.filter.codec.ProtocolDecoderAdapter;
	import ogs.lib.mina.filter.codec.ProtocolDecoderOutput;
	
	public class MsgDecoder extends ProtocolDecoderAdapter
	{
		private static const HEADER_LENGTH:int = 8;
		
		private var incomplete:Boolean = false;
		private var pcode:int = 0;
		private var len:int = 0;
		
		override public function decode(indata:ByteArray, out:ProtocolDecoderOutput):void
		{
			do 
			{
				if (!incomplete && indata.bytesAvailable >= HEADER_LENGTH)
				{
					pcode = indata.readInt();
					len = indata.readInt();
					
					incomplete = true;
				}
				
				if (incomplete && indata.bytesAvailable >= len)
				{
					var dataStr:String = indata.readUTFBytes(len);
					
					var msg:GameMsg = new GameMsg();
					msg.pcode = pcode;
					msg.body = JSON.decode(dataStr);
					
					out.write(msg);
					
					incomplete = false;
				}
			}
			while (!incomplete && indata.bytesAvailable >= HEADER_LENGTH);
		}
	}
}